package by.abolut.carpool.controller;

import by.abolut.carpool.domain.Requester;
import by.abolut.carpool.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


/**
 * Created by Andrey on 01.10.2014.
 */
@Controller
@RequestMapping("/")
public class IndexController {

    @Autowired
    private IUserService userService;

    /**
     * Controllers method for showing index page.
     *
     * @return String to be processed by Tiles
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(HttpSession session) {
        Object userObject = session.getAttribute("user");
        if (userObject != null) {
            return "index";
        } else {
            return "login";
        }
    }

    @RequestMapping(value = "registration", method = RequestMethod.GET)
    public ModelAndView registration(HttpSession session) {
        ModelAndView mav = new ModelAndView();
        Object userObject = session.getAttribute("user");
        if (userObject == null) {
            mav.setViewName("registration");
            mav.addObject("emptyRequester", new Requester());
        } else {
            mav.setViewName("index");
        }
        return mav;

    }

    /**
     * Controllers method for save Requester to persistence value.
     *
     * @param session
     * @param user
     * @return
     */
    @RequestMapping(value = "registration", method = RequestMethod.POST)
    public ModelAndView doRegistration(HttpSession session, Requester user) {
        ModelAndView mav = new ModelAndView("index");
        userService.saveUser(user);
        return mav;
    }


}
